package com.tjvib.util.retrofit;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.tjvib.Constants;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitHelper {

    public static RetrofitHelper retrofitHelper = new RetrofitHelper();

    private static final int READ_TIME_OUT = 120;
    private static final int CONNECT_TIME_OUT = 120;
    private static final int WRITE_TIME_OUT = 120;
    private Retrofit mRetrofit;

    private RetrofitHelper() {
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient().newBuilder();

        // 设置超时时间
        httpClientBuilder.connectTimeout(CONNECT_TIME_OUT, TimeUnit.SECONDS);
        httpClientBuilder.readTimeout(READ_TIME_OUT, TimeUnit.SECONDS);
        httpClientBuilder.writeTimeout(WRITE_TIME_OUT, TimeUnit.SECONDS);

        //添加数据请求统一处理拦截器
        httpClientBuilder.addInterceptor(new BaseInterceptor());
        OkHttpClient client = httpClientBuilder.build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL).client(client)
                .addConverterFactory(CustomGsonConverterFactory.create())//添加自定义的CustomGsonConverterFactory 统一处理返回数据
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static RetrofitHelper getInstance() {
        return retrofitHelper;
    }

    public ApiInterface create() {
        return mRetrofit.create(ApiInterface.class);
    }
}
